# -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from home.model import User_Info
from home.model.user_info import User_Info_Serializer
from home.services.user_info_service import User_Info_Service
from home.utils.array_utils import ListTools
from home.utils.post_parameter_getter import ParamGetter


@csrf_exempt
def regist_new_user(request):
	"""
		新用户注册服务
		:param request:
		:return:
		"""
	if request.method == "POST":
		user_Info_Service = User_Info_Service()
		user = User_Info()
		user.id = ParamGetter.getParam(request, "id")
		user.name = ParamGetter.getParam(request, "p_name")
		user.email = ParamGetter.getParam(request, "p_email")
		user.nick_name = ParamGetter.getParam(request, "p_nick_name")
		# 密码单独设置
		# user.user_pwd = ParamGetter.getParam(request, "user_pwd")
		user.is_admin = ParamGetter.getParam(request, "is_admin", False)
		user.article_count = ParamGetter.getParam(request, "article_count", 0)
		user.create_time = ParamGetter.getParam(request, "create_time")
		# 查询用户email是否已经注册过了
		users = user_Info_Service.filter_with_condition(email=user.email)
		if ListTools.isNotEmpty(users):
			result = {"status": "error", "message": "用户email貌似已经注册过了！"}
		else:
			# 持久化到数据库中
			try:
				user_Info_Service.save_user(user)
				# 将用户信息放入session表示登录完成
				request.session["login_user_name"] = users.name
				request.session["login_user"] = json.dumps(User_Info_Serializer.to_json_object(user), ensure_ascii=False)
				result = {"status": "success", "message": "用户注册成功！"}
			except Exception as err:
				result = {"status": "error", "message": "用户注册时发生异常！"}
				import traceback
				print(traceback.format_exc())
		return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
def user_saver(request):
	"""
		用户信息保存服务
		:param request:
		:return:
		"""
	if request.method == "POST":
		user_Info_Service = User_Info_Service()
		user = User_Info()
		user.id = ParamGetter.getParam(request, "id")
		user.name = ParamGetter.getParam(request, "p_name")
		user.email = ParamGetter.getParam(request, "p_email")
		user.nick_name = ParamGetter.getParam(request, "p_nick_name")
		# 密码单独设置
		# user.user_pwd = ParamGetter.getParam(request, "user_pwd")
		user.is_admin = ParamGetter.getParam(request, "is_admin", False)
		user.article_count = ParamGetter.getParam(request, "article_count", 0)
		user.create_time = ParamGetter.getParam(request, "create_time")
		# 查询用户email是否已经注册过了
		users = user_Info_Service.filter_with_condition(email=user.email)
		if ListTools.isNotEmpty(users):
			result = {"status": "error", "message": "用户email貌似已经注册过了！"}
		else:
			# 持久化到数据库中
			try:
				user_Info_Service.save_user(user)
				result = {"status": "success", "message": "用户添加完成！"}
			except Exception as err:
				result = {"status": "error", "message": "用户添加时发生异常！"}
				print(err)
		return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
def users_filter(request):
	"""
		用户信息搜索查询服务：根据过滤条件搜索用户信息列表，分页
		:param request:
		:return:
		"""
	if request.method == "PUT":
		filter_parameters = {}
		field_names = ["id", "name", "email", "nick_name", "is_admin"]
		user_Info_Service = User_Info_Service()
		for field_name in field_names:
			parameter_value = ParamGetter.getParam(request, field_name)
			if parameter_value is not None:
				filter_parameters[field_name] = parameter_value
		users = user_Info_Service.filter_with_condition(**filter_parameters)
		if ListTools.isNotEmpty(users):
			json_data = json.dumps(User_Info_Serializer.to_json_objects(users), ensure_ascii=False)
			result = {"status": "success", "message": "用户信息查询成功！", "users":json_data}
		else:
			result = {"status": "success", "message": "用户信息查询成功！", "users": []}
		return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
def user_operator(request, id):
	"""
	用户信息查询服务：根据用户ID查询或者删除指定的用户信息
	:param request:
	:return:
	"""
	if request.method == "GET":
		user_Info_Service = User_Info_Service()
		user = user_Info_Service.get_with_id(id)
		if user is not None:
			result = {"status": "success", "message": "用户信息查询成功！",
			          "user": json.dumps(User_Info_Serializer.to_json_object(user), ensure_ascii=False)}
		else:
			result = {"status": "error", "message": "用户信息不存在！ID=" + id}
	if request.method == "DELETE":
		user_Info_Service = User_Info_Service()
		if user_Info_Service.delete_user(id):
			result = {"status": "success", "message": "用户信息删除成功！ID=" + id}
		else:
			result = {"status": "error", "message": "用户信息删除失败！ID=" + id}
	return HttpResponse(json.dumps(result), content_type="application/json")
